/**
 * 数据返回层
 *  解密:
 *  JSON.parse(Crypt.source.DES.decrypt(encrypted,"webxue").toString(Crypt.source.enc.Utf8))
 * */

import { UtilTool } from "src/tools/util.tool";
import { StatusCode } from "src/utils/Mapping";
import { CryptoTool } from "src/tools/crypto.tool";
import configuration from "src/config/configuration";

export class Vo {
  // 加密密钥
  static secret = "webxue";
  // 是否返回加密值
  static isEncrypt = true;

  static success(
    data: any = "",
    message = "访问成功",
    code = StatusCode.Success
  ) {
    const result = UtilTool.transformResponseData({ code, message, data });
    return configuration().IS_ENCRYPT
      ? CryptoTool.encryptDbData(result)
      : result;
  }

  static error(
    message = "访问失败",
    error = null,
    data = {},
    code = StatusCode.Fail,
  ) {
    const result = UtilTool.transformResponseData({
      code,
      message,
      data: data,
    }) as FailResponse;
    if (configuration().IsDev) result.error = error;
    return configuration().IS_ENCRYPT
      ? CryptoTool.encryptDbData(result)
      : result;
  }

  static page(
    data: PageSuccData = {},
    message = "获取列表成功",
    code = StatusCode.Success,
  ) {
    data = UtilTool.transformResponseData({
      page: data.page,
      limit: data.limit,
      total: data.total,
      list: data.list,
    });
    const result = { code, message, data };

    return configuration().IS_ENCRYPT
      ? CryptoTool.encryptDbData(result)
      : result;
  }

  static upload(
    data: UploadSuccData,
    message = "上传成功",
    code: number = StatusCode.Success,
  ) {
    const result = {
      code,
      message,
      data: {
        id: data.id,
        fileUrl: data.fileUrl,
        fileUrlAll: data.fileUrlAll,
        filePath: data.filePath || data.fileUrlAll,
      },
    };
    return configuration().IS_ENCRYPT
      ? CryptoTool.encryptDbData(result)
      : result;
  }

}

// 响应基础结果
export interface ResponseProp {
  code: number;
  data: any;
  message: string;
}

// 失败响应
export interface FailResponse extends ResponseProp {
  error?: any;
}

// 分页响应
export interface PageSuccResponse extends ResponseProp {
  data: PageSuccData;
}

// 上传响应
export interface UploadSuccResponse extends ResponseProp {
  data: UploadSuccData;
}

// 分页响应data
export interface PageSuccData {
  page?: number;
  limit?: number;
  total?: number;
  list?: Array<any>;
}

// 上传响应data
export interface UploadSuccData {
  // 文件上传相对路径
  fileUrl: string;
  // 文件上传绝对路径(七牛云携带e&token参数)
  fileUrlAll: string;
  // fileUrlAll的补充(七牛云携带id参数)
  filePath?: string;
  // 文件上传的id
  id?: string;
}

// 入参
export interface Parameter {
  parameter?: {
    [key: string]: any;
  };
  // 兼容初始参数
  [key: string]: any;
}
